#include "stdafx.h"
#include "ElementPool.h"
#include <assert.h>
#include <mutex>


ElementPool::ElementPool()
{
    assert(_instance == nullptr);

    _instance = this;
}

uint32_t ElementPool::add(const QString &elementStr, const QString &tabStr)
{
    return instance()->_add(elementStr, tabStr);
}

Element ElementPool::at(uint32_t id)
{
    return instance()->_at(id);
}

void ElementPool::free(uint32_t id)
{
    return instance()->_free(id);
}

uint32_t ElementPool::_add(const QString &elementStr, const QString &tabStr)
{
    std::lock_guard<std::mutex> lock(locker);
    elements.emplace(lastIndex, Element{ elementStr, tabStr });
    return lastIndex++;
}

Element ElementPool::_at(uint32_t id)
{
    return elements.at(id);
}

void ElementPool::_free(uint32_t id)
{
    std::lock_guard<std::mutex> lock(locker);
    elements.erase(id);
}

ElementPool * ElementPool::instance()
{
    if (_instance == nullptr)
        _instance = new ElementPool;
    return _instance;
}

ElementPool * ElementPool::_instance = nullptr;
